import { ref, nextTick, onMounted, type Ref } from 'vue'

interface UseEditorReturn {
  scrollToBottom: () => Promise<void>
  getFootHeight: (placeholderHeight: Ref<string>) => Promise<void>
}

interface KeyboardReturn {
	height: number
}

/**
 * 编辑Hook
 */ 
export function useEditor(): UseEditorReturn {
	const scrollTop = ref(10000)
	
	// 滚动到底部
	async function scrollToBottom(): Promise<void> {
		const cpages = getCurrentPages()
		const croute = cpages[cpages.length - 1]?.route
		if(!(croute.includes('pages/chat/single') || croute.includes('pages/chat/group'))){
			return
		}
		
		await nextTick()
		await uni.pageScrollTo({
			scrollTop: scrollTop.value,
			duration: 0
		})
		scrollTop.value += 1000
	}
	
	// 获取底部高度
	async function getFootHeight(placeholderHeight: Ref<string>, isBottom: Boolean=true): Promise<void> {
		await nextTick()
		await new Promise(resolve => setTimeout(resolve, 20))
		
		const query = uni.createSelectorQuery()
		const rect: any = await new Promise((resolve) => {
			query.select('.xbc-editor').boundingClientRect(resolve).exec()
		})
		placeholderHeight.value = `${rect?.height}px`
		isBottom && await scrollToBottom()
	}
	
	// 监听键盘高度变化
	function listenKeyboard(res: KeyboardReturn) {
		if(res.height > 0) {
			uni.setStorageSync('uni_keyboard_height', res.height)
			// #ifndef H5
			uni.offKeyboardHeightChange(listenKeyboard)
			// #endif
		}
	}
	
	onMounted(() => {
		scrollToBottom()
		// #ifndef H5
		uni.onKeyboardHeightChange(listenKeyboard)
		// #endif
	})
	
	return {
		scrollToBottom,
		getFootHeight,
	}
}